<template>
  <div class="login-container">
    <el-dialog title="修改密码" :visible.sync="dialogVisible" width="600px" :show-close="false">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-position="left"
        label-width="120px"
        class="ruleForm"
      >
        <el-form-item label="手机号:" prop="tel ">
          <el-input
            ref="tel"
            v-model="ruleForm.tel"
            placeholder="请输入手机号"
            clearable
            name="tel"
            type="text"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="验证码:" prop="messageCode">
          <el-input
            ref="messageCode"
            v-model="ruleForm.messageCode"
            placeholder="请输入验证码"
            clearable
            name="messageCode"
            type="text"
            autocomplete="off"
          />
          <div class="codeText hand" :class="[{'active': btnDisabled}]" @click="getCodeFn('修改')">{{ btnDisabled ? captchaTime
            +
            '秒后重试' : '获取验证码' }}</div>
        </el-form-item>
        <el-form-item label="新密码:" prop="passwd">
          <el-input v-model="ruleForm.passwd" clearable type="password" />
        </el-form-item>
        <el-form-item label="确认密码:" prop="rePasswd">
          <el-input v-model="ruleForm.rePasswd" clearable type="password" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="submitForm('ruleForm')">提 交</el-button>
      </span>
    </el-dialog>
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form desktop row">
      <div class="right">
        <div class="title">
          <img src="@/assets/images/logo_mini.png" alt="">
        </div>
        <div class="titleZ">膏珍堂配方系统</div>
        <div v-if="switchBtn">
          <el-form-item prop="loginname" class="formItem">
            <div class="inputName">账号</div>
            <el-input
              ref="loginname"
              v-model="loginForm.loginname"
              placeholder="请输入登录账号"
              clearable
              name="loginname"
              type="text"
              autocomplete="off"
              @keyup.enter.native="handleLogin"
            />
          </el-form-item>
          <el-form-item prop="passwd" class="formItem">
            <div class="inputName">密码</div>
            <el-input
              :key="passwordType"
              ref="passwd"
              v-model="loginForm.passwd"
              clearable
              :type="passwordType"
              placeholder="请输入登录密码"
              name="passwd"
              autocomplete="off"
              class="password"
              @keyup.enter.native="handleLogin"
            />
            <div class="show-pwd" @click="showPwd">
              <div class="iconI">|</div>
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </div>
          </el-form-item>
          <el-form-item prop="imageCode" class="formItem verifyCode">
            <div class="inputName">验证码</div>
            <el-input
              ref="imageCode"
              v-model="loginForm.imageCode"
              placeholder="请输入验证码"
              clearable
              name="imageCode"
              type="text"
              autocomplete="off"
              @keyup.enter.native="handleLogin"
            />
            <div class="verifyImg hand" @click="getCode">
              <img :src="verifyImg" alt="点击刷新">
            </div>
          </el-form-item>
        </div>
        <div v-else>
          <el-form-item prop="tel " class="formItem">
            <div class="inputName">手机号</div>
            <el-input
              ref="tel"
              v-model="loginForm.tel"
              placeholder="请输入手机号"
              clearable
              name="tel"
              type="text"
              autocomplete="off"
              @keyup.enter.native="handleLogin"
            />
          </el-form-item>
          <el-form-item prop="messageCode" class="formItem">
            <div class="inputName">验证码</div>
            <el-input
              ref="messageCode"
              v-model="loginForm.messageCode"
              placeholder="请输入验证码"
              clearable
              name="messageCode"
              type="text"
              autocomplete="off"
              @keyup.enter.native="handleLogin"
            />
            <div class="codeText hand" :class="[{'active': btnDisabled}]" @click="getCodeFn('登录')">{{ btnDisabled ? captchaTime
              +
              '秒后重试' : '获取验证码' }}</div>
          </el-form-item>
        </div>
        <el-button :loading="loading" type="primary" class="btn fz20" @click.native.prevent="handleLogin">登 录
        </el-button>
        <!-- <div v-if="switchBtn" class="tc mt30 c666 hand switch" @click="clickSwitch">验证码登录</div> -->
        <!-- <div v-else class="tc mt30 c666 hand switch" @click="clickSwitch">账号密码登录</div> -->
      </div>
    </el-form>

  </div>
</template>

<script>
import { validatePhone } from '@/utils/validate';
import { usersMenuList } from '@/api/account';
import { getToken } from '@/utils/auth';
import { getTicket, getImageCode, getTelCode, resetUserPasswd } from '@/api/user';

class LoginForm {
  loginname = '';
  passwd = '';
  imageCode = '';
  tel = '';
  messageCode = '';
}
export default {
  name: 'Login',
  data() {
    const tel = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'));
      }
    };
    const messageCode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('验证码不能为空'));
      }
    };
    // const oldPass = (rule, value, callback) => {
    //   if (!value) {
    //     return callback(new Error('原密码不能为空'));
    //   }
    // };
    const newPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'));
      } else {
        if (this.ruleForm.rePasswd !== '') {
          this.$refs.ruleForm.validateField('rePasswd');
        }
        callback();
      }
    };
    const rePasswd = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.passwd) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      loginForm: new LoginForm(),
      loginRules: {
        loginname: [
          { required: true, message: '请输入正确的用户名', trigger: 'blur' }
        ],
        passwd: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, message: '密码不能少于6位', trigger: 'blur' }
        ],
        imageCode: [
          { required: true, message: '验证码不能为空', trigger: 'blur' }
        ],
        tel: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        messageCode: [
          { required: true, message: '验证码不能为空', trigger: 'blur' }
        ]
      },
      loading: false,
      dialogVisible: false,
      passwordType: 'password',
      codeImg: '',
      verifyImg: '',
      switchBtn: false,
      labelPosition: 'top',
      // 防止验证码按钮重复点击
      btnDisabled: false,
      // 验证码定时器
      interval: null,
      // 验证码倒计时
      captchaTime: 60,
      // 固定时间
      fixedSecond2: 60,
      ruleForm: {
        tel: '',
        messageCode: '',
        userId: '',
        passwd: '',
        rePasswd: ''
      },
      rules: {
        tel: [{ validator: tel, trigger: 'blur' }],
        messageCode: [{ validator: messageCode, trigger: 'blur' }],
        passwd: [{ validator: newPass, trigger: 'blur' }],
        rePasswd: [{ validator: rePasswd, trigger: 'blur' }]
      },
      firstLogin: 0 // 是否第一次登录

    };
  },
  mounted() {
    // this.ruleForm.userId = getToken('session_id');
    this.getCode();
    // 获取上一次点击验证码的时间
    let startTime = sessionStorage.getItem('startTime');
    let num = (new Date().getTime() - startTime) / 1000;
    let second = this.fixedSecond2 - parseInt(num);
    // console.log(second, 'second----');
    // console.log('外部链接----', window.server);
    // 当重进登录页面或者登录页面被刷新后拿到上一次点击验证码的时间。如果没过期，则接着走倒计时,而不是从60秒重新开始倒计时
    if (second > 0) {
      this.btnDisabled = true;
      this.captchaTime = second;
      this.countdownFun60();
    }
    console.log(111111);
  },
  methods: {
    // 获取图形验证码
    async getCode() {
      // 获取命令牌
      this.loginForm.ticket = await getTicket();
      const res = await getImageCode({ ticket: this.loginForm.ticket });
      this.verifyImg = window.URL.createObjectURL(res);
    },
    // 切换密码显示隐藏
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = '';
      } else {
        this.passwordType = 'password';
      }
      this.$nextTick(() => {
        this.$refs.passwd.focus();
      });
    },
    // 切换登录方式
    clickSwitch() {
      this.loginForm = new LoginForm();
      this.$refs.loginForm.resetFields();
      this.switchBtn = !this.switchBtn;
    },
    // 获取手机验证码
    getCodeFn(type) {
      let tel = type == '登录' ? this.loginForm.tel : this.ruleForm.tel;
      if (!tel) {
        this.$notify.error({
          title: '提示',
          message: '请输入手机号'
        });
        return;
      } else if (!/^1[3-9]\d{9}$/.test(tel)) {
        this.$notify.error({
          title: '提示',
          message: '请输入有效手机号'
        });
        return;
      }

      // 防止重复点击
      if (this.btnDisabled) return;
      this.btnDisabled = true;
      this.countdownFun60(type);
      this.getTelCode(type);
      // 验证码点击的时间
      sessionStorage.setItem('startTime', new Date().getTime());
    },

    // 手机验证码60秒倒计时
    countdownFun60(type) {
      this.interval = setInterval(() => {
        this.captchaTime = this.captchaTime - 1;
        if (this.captchaTime === 0) {
          clearInterval(this.interval);
          this.btnDisabled = false;
          this.captchaTime = this.fixedSecond2;
        }
      }, 1000);
    },
    // 获取手机验证码
    async getTelCode(type) {
      // console.log(sessionStorage.getItem('brand'));
      this.loginForm.ticket = await getTicket();
      let tel = type == '登录' ? this.loginForm.tel : this.ruleForm.tel;
      const res = await getTelCode({
        tel,
        ticket: this.loginForm.ticket
      });
      // console.log(res);
    },

    // 登录
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch('user/login', this.loginForm)
            .then(() => {
              this.getUserData();
            }).catch(() => {
              this.loading = false;
            });
        } else {
          console.log('检验失败');
          return false;
        }
      });
    },
    // 获取用户信息
    async getUserData() {
      const res = await usersMenuList({
        clientType: 0,
        userId: 1
      });
      // console.log(res);
      this.loading = false;
      // this.$router.push({ path: '/archives' });

      // console.log(this.$router);
      // console.log(this.$store.getters.menuAll);

      this.ruleForm.userId = getToken('session_id');
      this.firstLogin = getToken('firstLogin');
      // this.$router.push({ path: '/archives/drugs/index' });
      // // }
      // console.log(this.$router);
      // console.log(this.$store.getters);
      // let path = this.$store.getters.firstPath;
      // if (!path) {
      //   this.$notify.error({
      //     title: '提示',
      //     message: '暂无登录权限，请联系管理员开通！！！'
      //   });
      //   return;
      // }
      // console.log('------', path);
      this.$router.push({ path: '/archives/formula' });
    },
    // 登录
    // handleLogin() {
    //   this.$refs.loginForm.validate((valid) => {
    //     if (valid) {
    //       this.loading = true;
    //       this.getLogin();
    //     } else {
    //       console.log('检验失败');
    //       return false;
    //     }
    //   });
    // },
    // async getLogin() {
    //   let data = {
    //     ticket: sessionStorage.getItem('brand'),
    //     loginname: 'zhangsanfeng',
    //     passwd: '123456',
    //     imageCode: 'QF3R'
    //   };
    //   // console.log(this.loginForm);
    //   const res = await accountLogin({ ticket: sessionStorage.getItem('brand'), ...this.loginForm });
    //   setToken('auth_key', res.token);
    //   setToken('session_id', res.userId);
    //   // console.log(getToken('auth_key'), getToken('session_id'));
    //   let path;
    //   // console.log(this.menus);
    //   // if (
    //   //   this.menus.length > 0 &&
    //   //   this.menus[0].children.length > 0
    //   // ) {
    //   //   path = this.menus[0].children[0].path;
    //   // } else {
    //   //   path = '/archives/drugs/index';
    //   // }
    //   // this.$router.push({ path: path });
    //   this.$router.push({
    //     path: '/archives/drugs/index'
    //   });
    //   this.loading = false;
    // },
    // 切换登陆模式
    changeMode(type) {
      if (type === 'wechat') { return this.$message.warning('微信扫码登录暂未开放！'); }
      this.loginForm.grant_type = type;
    },
    submitForm(formName) {
      if (!this.ruleForm.tel) {
        return this.$message.info('请输入手机号');
      }
      if (!this.ruleForm.messageCode) {
        return this.$message.info('请输入验证码');
      }
      if (!this.ruleForm.passwd) {
        return this.$message.info('请输入新密码');
      }
      if (!this.ruleForm.rePasswd) {
        return this.$message.info('请确认密码');
      }
      if (this.ruleForm.passwd !== this.ruleForm.rePasswd) {
        return this.$message.info('两次密码输入不一致');
      } else {
        this.hint('passwd', '修改密码');
      }
    },
    // 确认提示
    hint(status, hintText, row) {
      this.$confirm(`${hintText}, 是否确认?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          switch (status) {
            case 'passwd':
              this.submitPas();
              break;
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    },
    async submitPas() {
      // console.log(this.ruleForm);
      const { msg } = await resetUserPasswd({ ...this.ruleForm, ticket: this.ticket, clientType: 0 });
      this.$notification('操作成功', 'success', msg);
    }
  }
};
</script>

<style lang="scss" scoped>
$bg: #bf3f3f;
$dark_gray: #889aa4;
$light_gray: #eee;
$zoom: 937 / 1080;

.login-container {
  position: relative;
  min-height: 100%;
  width: 100%;
  // background-color: $bg;
  background: url("../../assets/images/logo_bg.png") no-repeat #fff;
  background-size: auto 100%;
  overflow: hidden;
  display: flex;
  .left {
    zoom: $zoom;
    position: absolute;
    top: 46%;
    left: 25%;
    transform: translate(-25%, -50%);
    width: 516px;
    height: 392px;
    img {
      width: 100%;
      height: 100%;
      display: inline-block;
    }
  }
  // PC端样式
  .login-form.desktop {
    // zoom: $zoom;
    // position: absolute;
    // top: 46%;
    // left: 74%;
    // transform: translate(-74%, -46%);
    // width: 500px;
    // height: 600px;
    // max-height: 100vh;
    // max-width: 100%;
    // background: url("../../assets/images/login-logo.png") no-repeat 14% center / 450px 449px #fff;
    // background: 14% center / 450px 449px #fff;
    // border-radius: 20px;
    // box-shadow: 3px 3px 16px 3px #f6e4e0a9;

    .right {
      zoom: $zoom;
      position: absolute;
      top: 50%;
      left: 68%;
      transform: translate(0%, -50%);
      // width: 500px;
      // height: 100%;
      // padding: 40px 60px 120px;
      .title {
        text-align: center;
        img {
          width: 118px;

          height: 118px;
        }
      }
      .titleZ {
        text-align: center;
        font-size: 34px;
        font-weight: bold;
        line-height: 60px;
        margin-bottom: 20px;
        margin: 10px 0 60px;
        color: #8b2e2f;
      }
      .inputName {
        margin-top: 2px;
        color: #bf3f3f;
        padding-left: 3px;
        font-weight: bold;
        line-height: 50px;
      }
      .inputName::before {
        width: 5px;
        height: 6px;
        margin-right: 10px;
        content: "|";
        font-weight: bold;
        background: #bf3f3f;
      }
      .formItem {
        background: #f6e4e0;
        border-radius: 30px;
        margin-bottom: 40px;
        position: relative;
        ::v-deep.el-form-item__content {
          display: flex;
          padding-left: 30px;
          // justify-content: space-between;
        }
        ::v-deep.el-input {
          width: 78%;
        }
        ::v-deep.el-input--suffix .el-input__inner {
          color: #8b2e2f;
          font-weight: bold;
        }
        ::v-deep.password.el-input {
          width: 75%;
        }
        .codeText {
          position: absolute;
          right: 20px;
          top: 6px;
          color: #bf3f3f;
        }
      }

      .verifyCode {
        width: 240px;
        // height: 100px;
        // padding: 20px 0 30px;
        border-radius: 30px 3px 3px 30px;
        position: relative;
        ::v-deep.el-input {
          width: 70%;
        }
        .verifyImg {
          position: absolute;
          right: -166px;
          top: 0px;
          img {
            width: 160px;
            height: 52px;
          }
        }
      }
      .mode {
        display: flex;
        justify-content: flex-start;
        .mode-item {
          color: #93a0ae;
          font-size: 26px;
          line-height: 46px;
        }
        .mode-item.selected {
          color: #48a0ff;
          border-bottom: 2px solid #48a0ff;
        }
      }
      .show-pwd {
        position: absolute;
        right: 15px;
        top: 52%;
        transform: translateY(-52%);
        font-size: 18px;
        color: #8b2e2f;
        cursor: pointer;
        user-select: none;
        display: flex;
      }
      .iconI {
        color: #8b2e2f;
      }
      .svg-icon {
        margin: 10px 0 0 6px;
      }
      .code-img {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        width: 120px;
        height: 40px;
        cursor: pointer;
      }
      .btn {
        width: 400px;
        height: 54px;
        display: block;
        border-radius: 35px;
        margin: 64px auto 0;
        background: $bg;
        border-color: $bg;
      }
    }
  }
  .tip {
    font-size: 20px;
    color: #fff;
    position: fixed;
    bottom: 30px;
    left: 50%;
    transform: translateX(-50%);
  }
}
::v-deep.el-form-item.is-error .el-input__inner,
.el-form-item.is-error .el-input__inner:focus,
.el-form-item.is-error .el-textarea__inner,
.el-form-item.is-error .el-textarea__inner:focus,
.el-message-box__input input.invalid,
.el-message-box__input input.invalid:focus {
  background: #f6e4e0a9 !important;
}
::v-deep input::-webkit-input-placeholder {
  -webkit-text-fill-color: #bf3f3f9a;
}
::v-deep input::-moz-input-placeholder {
  -webkit-text-fill-color: #bf3f3f9a;
}
::v-deep input::-ms-input-placeholder {
  -webkit-text-fill-color: #bf3f3f9a;
}
::v-deep[data-v-37dfd6fc].el-form-item.is-error .el-input__inner,
.el-form-item.is-error .el-input__inner[data-v-37dfd6fc]:focus,
.el-form-item.is-error .el-textarea__inner[data-v-37dfd6fc],
.el-form-item.is-error .el-textarea__inner[data-v-37dfd6fc]:focus,
.el-message-box__input input.invalid[data-v-37dfd6fc],
.el-message-box__input input.invalid[data-v-37dfd6fc]:focus {
  border: 0 !important;
  height: 50px;
}
::v-deep.el-input--suffix .el-input__inner {
  height: 52px !important;
  background: #f6e4e0a9 !important;
  border: 0 !important;
}
::v-deep.el-input--suffix.password .el-input__inner {
  width: 90% !important;
}
.remember {
  text-align: right;
  color: #bf3f3f;
}
// input:-webkit-autofill {
::v-deep .el-form-item__error {
  color: #f56c6c;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
  position: absolute;
  top: 100%;
  left: 0px;
  margin-left: 40px !important;
}
.switch:hover {
  color: #bf3f3f;
}
::v-deep.el-dialog__wrapper {
  background: #000;
}
.ruleForm {
  .codeText {
    position: absolute;
    right: 50px;
    top: 0px;
    font-size: 12px;
    color: #bf3f3f;
  }
  ::v-deep.el-input--suffix .el-input__inner {
    height: 40px !important;
    width: 300px;
  }
  ::v-deep.el-form-item__error {
    margin-left: 0px !important;
  }
}
</style>
